package com.kinghunt.misp.web.context;

import com.kinghunt.misp.common.exception.AnonymousUserException;
import org.springframework.http.HttpStatus;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ApiContextFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        try {
            ApiContext.init(httpServletRequest);
            filterChain.doFilter(httpServletRequest, httpServletResponse);
        } catch (AnonymousUserException e) {
            httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
        } finally {
            ApiContext.cleanContext();
        }
    }
}
